<template>
  <!-- 项目管理：文档内容 -->
  <div style="width:100%;height:100%;background:#E9E9E9;">
    <el-progress :percentage="percentage" :show-text="false" v-show="percentage<100"></el-progress>
    <div class="mainPart" :class="device==='mobile'?'mobileMainPart':''">
      <div class="mainItem menuPart">
        <el-tree ref="structureTree" :data="structureList" empty-text="暂无数据" :render-after-expand="false"
          node-key="id" :props="defaultProps" :render-content="renderTree" @node-click="chooseStructure"></el-tree>
      </div>
      <div class="mainItem mainContent">
        <div :style="{'font-size':currentFontSize+'px'}" v-if="Object.keys(contentHtml).length">
          <div v-for="vo in structureArr" :key="vo.cateId"
              v-html="contentHtml['contentPart'+vo.cateId]?contentHtml['contentPart'+vo.cateId]:'<span style=\'color:#EEE\'>加载中...</span>'"></div>
        </div>
        <div id="noData" v-if="!Object.keys(contentHtml).length">暂无内容</div>
        <!-- <div id="buttonGroup">
          <el-input-number v-model="currentFontSize" @change="fontSizeChange" v-if="Object.keys(contentHtml).length"
              :min="14" :max="24" size="small" controls-position="right"></el-input-number>
          <el-button type="primary" plain size="small">全文共{{ totalCount }}字</el-button>
          <el-tooltip placement="left" effect="light" v-show="noDataCateId.length">
            <div slot="content">
              <el-tag type="danger">您还有未填写的文档内容，已在左侧的目录处显示为红色字体。</el-tag>
            </div>
            <el-button type="danger" plain size="small">共{{ noDataCateId.length }}处未填写</el-button>
          </el-tooltip>
          <el-tooltip content="刷新" placement="right" effect="light">
            <el-button type="primary" icon="el-icon-refresh" circle @click="getStructureList"></el-button>
          </el-tooltip>
        </div> -->
        <el-button id="backToTop" type="primary" icon="el-icon-top" circle @click="backToTop" v-show="isShowTopBtn"></el-button>
      </div>
    </div>
  </div>
</template>

<script>
  import { Loading } from 'element-ui';
  import { mapGetters } from 'vuex';
  import { formatData } from '@/api/common/common';
  import { listContMenu } from "@/api/project/contentMenu";
  import { listContentInfo } from "@/api/project/contentInfo";

  export default {
    name: 'ProjectWordPreview',
    data(){
      return {
        projectId:this.$route.query.projectId,
        structureArr:[],  // 扁平化数据格式的目录结构
        structureList:[], // 树形结构的目录结构
        defaultProps:{
          label: 'cateName',
          children: 'children'
        },
        cateId:"",
        currentCate:"",
        currentContentList:[],  // 当前节点处的内容
        contId:"",  // 当前选中文本块
        currentFontSize:16, // 当前文本字号
        nodeList:[],  // 所有子节点的cateId
        titleNoObj:{},  // 标题编号
        noDataCateId:[],
        contentHtml:{},
        isShowTopBtn:false, // 是否显示回到顶部按钮
        totalCount:0, // 字数统计
        // 进度条
        percentage:0, // 加载进度
        totalLoadNum:0, // 预计加载总数
        finishLoadNum:0 // 已加载数目
      }
    },
    computed: {
      ...mapGetters([ 'device' ])
    },
    created(){
      this.getStructureList();
    },
    mounted(){
      this.$nextTick(()=>{
        window.addEventListener("scroll", this.scrollEvent);
      })
    },
    activated(){
      this.projectId = this.$route.query.projectId;
    },
    methods:{
      // 获取文档结构
      getStructureList(){
        listContMenu({
          projectId:this.projectId
        }).then(ret=>{
          this.structureArr = ret.rows;
          this.totalLoadNum = ret.rows.length;
          this.structureList = formatData(ret.rows, 0, 1);
          this.addTitleNo(ret.rows);
        }).catch();
      },

      // 添加标题编号
      addTitleNo(info){
        console.log("info", info);
        let data = info;
        this.titleNoObj = {};
        data[0].titleNo = "1";
        this.titleNoObj["level"+data[0].cateLevel] = [];
        this.titleNoObj["level"+data[0].cateLevel].push("1");
        this.contentHtml["contentPart"+data[0].cateId] = "<h3 id='cateId_"+data[0].cateId+"'>1 "+data[0].cateName+"</h3>";
        this.finishLoadNum = 1;
        this.percentage = Number((this.finishLoadNum/this.totalLoadNum*100).toFixed(0));
        if(data[0].cateType == 2) this.getContentInfo(data[0].cateId);
        for(let i = 0; i < data.length; i++){
          this.totalCount += data[i].cateName.length;
          if(i != 0){
            if(!this.titleNoObj["level"+data[i].cateLevel]) this.titleNoObj["level"+data[i].cateLevel] = [];
            if(data[i].cateLevel > data[i-1].cateLevel){
              data[i].titleNo = String(data[i-1].titleNo)+".1";
            }else if(data[i].cateLevel == data[i-1].cateLevel){
              let arr = data[i-1].titleNo.indexOf(".")==-1?[data[i-1].titleNo]:data[i-1].titleNo.split(".");
              arr[arr.length-1] = Number(arr[arr.length-1]) + 1;
              data[i].titleNo = arr.join(".");
            }else{
              let obj = this.titleNoObj["level"+data[i].cateLevel][this.titleNoObj["level"+data[i].cateLevel].length-1];
              let arr = String(obj).indexOf(".")==-1?[obj]:obj.split(".");
              arr.slice(arr.length-1,1);
              arr[arr.length-1] = Number(arr[arr.length-1]) + 1;
              data[i].titleNo = arr.join(".");
            }
            this.totalCount += data[i].titleNo.length;
            this.titleNoObj["level"+data[i].cateLevel].push(data[i].titleNo);
            this.contentHtml["contentPart"+data[i].cateId] = "<h3 id='cateId_"+data[i].cateId+"'>"+data[i].titleNo+" "+data[i].cateName+"</h3>";
            // if(data[i].cateType == 2){
              this.getContentInfo(data[i].cateId);
            // }else{
            //   this.finishLoadNum++;
            //   this.percentage = Number((this.finishLoadNum/this.totalLoadNum).toFixed(0))*100;
            // }
          }
        }
      },

      // 渲染树形结构
      renderTree(h, { node, data, store }){
        console.log(node)
        console.log(data)
        if(data.children.length){
          return (
            <span class="custom-tree-node parentNode">{node.label}</span>
          );
        }else{
          if(this.noDataCateId.includes(data.cateId)){
            return (
              <a class="custom-tree-node childNode" href={'#cateId_'+data.cateId} style="color:red;">{node.label}</a>
            );
          }else{
            return (
              <a class="custom-tree-node childNode" href={'#cateId_'+data.cateId}>{node.label}</a>
            );
          }
        }
      },

      // 选择结构
      chooseStructure(obj, node, treeComponent){
        this.cateId = obj.cateId;
        this.currentCate = obj.cateName;
      },

      // 获取文档内容
      getContentInfo(cateId){
        let loadingInstance = Loading.service({ fullscreen: true, background:"rgba(0,0,0,0.5)" });
        listContentInfo({
          projectId:this.projectId,
          cateId:cateId
        }).then(ret=>{
          if(ret.code == 200){
            if(ret.rows.length){
              var str = "";
              ret.rows.forEach((vo,index)=>{
                console.log("vo", vo);
                if(vo.contType == 1){
                  this.totalCount += vo.content.length;
                  str += "<p>"+vo.content+"</p>";
                }else if(vo.contType == 2 || vo.contType == 4){
                  console.log("content", JSON.parse(vo.content));
                  str += "<img src='"+JSON.parse(vo.content).url+"' style='max-width:554px;' />";
                  if(JSON.parse(vo.content).caption) str += "<p class='captionPart'>"+JSON.parse(vo.content).caption+"</p>";
                }else if(vo.contType == 3){
                  var cont = JSON.parse(vo.content);
                  str += '<table class="el-table el-table--fit el-table--border el-table--enable-row-hover el-table--enable-row-transition el-table--small el-table__body">'
                  for(let i = 0; i< cont.table.length; i++){
                    str += '<tr class="el-table__row"'+(i==cont.table.length-1?'style="border-bottom:none!important"':'')+'>'
                    for(var k = 0; k <cont.column.length; k++){
                      str +='<td class="el-table__cell" style="border-right:'+(k==cont.column.length-1?'none':'')+';border-bottom:'+(i==cont.table.length-1?'none':'')+'"><div class="cell">'+cont.table[i][cont.column[k].prop]+'</div></td>'
                    }
                    str += '</tr>'
                  }
                  str += '</el-table-column></table><p class="captionPart">'+(cont.caption || "")+'</p>'
                }else if(vo.contType == 5){
                  str += '<div>见运行手册：<a style="color:#1890ff;text-decoration:underline;text-indent:0;cursor:pointer;word-break:break-word;"'
                      + 'href="'+JSON.parse(vo.content).url+'" target="_blank">'+JSON.parse(vo.content).name+'</a></div>'
                }
                console.log("str", str);
                if(index == ret.rows.length-1){
                  this.contentHtml["contentPart"+cateId] += str;
                  console.log("contentHtml", this.contentHtml);
                }
              })
            }
            if(this.finishLoadNum == this.totalLoadNum) return false;
            this.finishLoadNum++;
            this.percentage = Number((this.finishLoadNum/this.totalLoadNum*100).toFixed(0));
          }else{
            this.$message.error(ret.msg);
          }
          loadingInstance.close();
        })
        .catch(err=>{
          console.log(err);
          loadingInstance.close();
        })
      },

      // 字号变化监听
      fontSizeChange(currentVal, oldVal){
        // console.log(currentVal, oldVal);
        // console.log(this.currentFontSize);
      },

      // 回到顶部
      backToTop(){
        scrollTo(0,0);
      },

      // 页面滚动监听
      scrollEvent(){
        let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTo;
        if(scrollTop > 200){
          this.isShowTopBtn = true;
        }else{
          this.isShowTopBtn = false;
        }
      }
    },
    destroyed(){
      window.removeEventListener("scroll", this.scrollEvent)
    }
  }
</script>

<style scoped>
  .mainPart{
    width:1140px;
    height:100%;
    min-height:calc(100vh - 84px);
    font-size:14px;
    margin:0 auto;
    padding: 10px 0;
    box-sizing:border-box;
  }
  .mainPart .mainItem{
    height:100%;
    min-height:500px;
    background-color:#FFF;
    padding:8px;
    overflow-y:auto;
    position:relative;
    box-sizing:border-box;
  }
  .mainPart .mainItem.menuPart{
    height:calc(100vh - 104px);
    width:300px;
    margin-right:10px;
    /* border-right:1px solid #303133; */
    position:fixed;
  }
  .el-tree >>> .el-tree-node{
    padding:4px 0;
    white-space:normal;
  }
  .mainPart .mainItem.mainContent{
    /*width:calc(100% - 310px);*/
    width: 794px;
    overflow-x: hidden;
    padding:15px 120px;
    margin-left:310px;
    position:relative;
  }
  .mainContent >>> span{
    display:inline-block;
    margin:0;
    text-indent:32px;
  }
  .mainContent >>> p{
    font-size:16px;
    line-height:28px;
    text-indent: 32px;
    margin:0;
  }
  #buttonGroup{
    width:90px;
    text-align:center;
    position:fixed;
    top:40px;
    right:calc((100% - 1140px) / 2 - 65px);
  }
  #buttonGroup .el-button{
    display:block;
    margin:10px auto;
  }
  #buttonGroup >>> span{
    text-indent:0;
    display:inline;
  }
  .mainPart >>> .el-tree-node.is-current:not(.is-expanded) .el-tree-node__content{
    color: #1890ff!important;
    background: #e8f4ff!important;
  }
  .cardBox{
    width:100%;
    color: #303133;
    border:1px solid #FFF;
    position:relative;
  }
  .cardBox:hover{
    border:1px solid #FAFAFA;
    border-radius:6px;
    /*background-color:#FAFAFA;*/
    background-color:#FFFFE7;
  }
  .cardBox .sortPart{
    width:65px;
    height:28px;
    line-height:28px;
    border:1px solid #CCC;
    position:absolute;
    left:-70px;
    box-sizing:content-box;
  }
  .cardBox .sortPart >>> .el-input__inner{
    width:100%;
    height:100%;
    font-size:16px;
    font-weight:bolder;
    padding: 0 5px;
    text-align: center;
    border: none;
  }
  .cardBox .sortInput{
    width: 60px;
    height:25px;
    text-align: center;
    border: none;
  }
  .cardBox input.sortInput:focus-visible{
    outline: none;
  }
  /* .cardBox .cardContent{
    width:calc(100% - 60px);
    padding-right:6px;
  } */
  .cardBox .cardContent >>> span{
    display:inline-block;
    margin:0;
    text-indent:32px;
  }
  .cardBox .signPart{
    width:96px;
    min-height:30px;
    border-left:2px solid #F56C6C;
    position:absolute;
    top:0;
    right:-100px;
    cursor:pointer;
  }
  .cardBox .signPart .el-button{
    font-size:12px;
    margin:0 3px;
    border: none;
  }
  .cardBox .signPart .el-button:hover{
    color: #F56C6C;
    border: none;
    /*color: #FFF;*/
    /*background-color: #1890ff;*/
  }
  .mainContent >>> p.captionPart{
    font-size:12px;
    color:#8B8585;
    text-align:center;
    text-indent:0;
  }
  .el-dropdown-menu >>> .el-dropdown-menu__item{
    width:100%!important;
    padding:0!important;
  }
  .el-dropdown-menu >>> .el-dropdown-menu__item div{
    width:100%;
    padding:0 17px;
  }
  .cardBox p{
    font-size:16px;
    text-indent: 32px;
    line-height:28px;
    margin:0;
  }
  .cardBox .el-image{
    object-fit:cover;
  }
  #noData{
    width:100px;
    height:24px;
    line-height:24px;
    text-align:center;
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    margin:auto;
  }
  .el-textarea{
    margin-bottom:8px;
  }
  #backToTop{
    position:fixed;
    bottom:40px;
    right:calc((100% - 1140px) / 2 - 38px);
  }

  /* 手机端 */
  .mobileMainPart{
    width:100%;
    overflow:hidden;
  }
  .mainPart.mobileMainPart .mainItem.menuPart{
    width:100%;
    min-height:150px;
    max-height:200px;
    height:200px;
    position:relative;
  }
  .mainPart.mobileMainPart .mainItem.mainContent{
    width:100%;
    height:calc(100% - 200px);
    margin:15px 0 0;
  }
  .mainPart.mobileMainPart .mainItem.mainContent{
    padding:48px 35px 96px;
  }
  .mainPart.mobileMainPart .mainItem.mainContent >>> img{
    width:100%;
  }
</style>